package com.code.test.first.link;

public class Code {

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode second = new ListNode(2);
        ListNode third = new ListNode(3);
        ListNode n4 = new ListNode(4);
        ListNode n5 = new ListNode(5);
        ListNode n6 = new ListNode(6);
        ListNode n7 = new ListNode(7);

        head.setNext(second);
        second.setNext(third);
        third.setNext(n4);
        n4.setNext(n5);
        n5.setNext(n6);
        n6.setNext(n7);

        ListNode node = reverseBetween(head, 2, 4);
        System.out.println("");

    }


    /**
     * 翻转链表中 从m到n的节点
     */
    public static ListNode reverseBetween(ListNode head, int m, int n) {
        // write code here

        ListNode pre = head;
        //先走m-1步
        for (int i = 0; i < m - 1; i++) {
            pre = pre.next;
        }
        ListNode leftNode = pre.next;
        //把pre下一个切断
        pre.next = null;

        ListNode rightNode = leftNode;
        for (int i = 0; i <= n - m; i++) {
            rightNode = rightNode.next;
        }
        //记录右下一节点
        ListNode rightNextNode = rightNode.next;
        //切断，暂存切断点
        ListNode cur = leftNode;
        ListNode curpre = null;
        //开始反转
        while (cur != null) {
            ListNode tmp = cur.next;
            cur.next = curpre;
            curpre = cur;
            cur = tmp;
        }
        //挂回原来
        pre.next = cur;
        rightNode.next = rightNextNode;


        return head;
    }
}
